import router from '@/router'
import {replaceDbBiasToSingle} from '@/utils'

export const APP_CONFIG = {
  isOAuth: false,
  oAuth: {
    login: {
      url: import.meta.env.VITE_SSOLOGIN_URL,
      redirectKey: 'service'
    },
    logout: {
      url: import.meta.env.VITE_SSOLOGOUT_URL,
      redirectKey: 'service'
    }
  },
  authKey: [{
    in: 'ticket',
    out: 'ticket'
  }]
}

const getLocalUrl = () => {
  const subUrl = import.meta.env.VITE_FRONT_SUBURL || ''
  return location.origin + replaceDbBiasToSingle(location.pathname.replace(subUrl, '') + subUrl) + location.hash
}

/**
 * 鉴权登录
 */
export const oAuthLogin = () => {
  const oAuth = APP_CONFIG.oAuth
  if (oAuth) {
    let localUrl = getLocalUrl()
    let obj = oAuth.login
    if (obj.url.indexOf('?') > -1) {
      location.assign(`${obj.url}&${obj.redirectKey}=${localUrl}`)
    } else {
      location.assign(`${obj.url}?${obj.redirectKey}=${localUrl}`)
    }
  }
}
/**
 * 鉴权退出登录
 */
export const oAuthLogout = () => {
  if (!APP_CONFIG.isOAuth) { // 不走sso退出登录
    return redirctToLogin()
  }
  const oAuth = APP_CONFIG.oAuth
  if (oAuth) {
    let obj = oAuth.logout
    let localUrl = getLocalUrl()
    if (obj.url.indexOf('?') > -1) {
      location.assign(`${obj.url}&${obj.redirectKey}=${localUrl}`)
    } else {
      location.assign(`${obj.url}?${obj.redirectKey}=${localUrl}`)
    }
  }
}

/**
 * 跳转至登录页
 */
export const redirctToLogin = (next?: Function) => {
  // 清除token
  if (APP_CONFIG.isOAuth) { // 发布环境login跳转
    oAuthLogin()
  } else { // 本地开发登录跳转
    if (next) {
      next('/login')
    } else {
      router.push({
        path: '/login',
        query: {
          refer: router.options.history.state.current as string
        }
      })
    }
  }
}

/**
 * 用户是否为登录状态
 * 此方法
 */
export const isUserLoggedIn = async () => {
  return true
}